﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;
using NHibernate.Tool.hbm2ddl;
using SinBiota.Model.Entities;
using Sinbiota.Model.Persistence.NHibernateMappings;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using FluentNHibernate.Automapping;
﻿

namespace SinBiota.Model.Persistence.SessionManager
{
    public class NHibernateSessionFactory
    {

        public static ISessionFactory CreateSessionFactory(string connectionString)
        {
            //Open a connection to the database 
             return Fluently.Configure()
                 .Database(
                     MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(connectionString))
                 .Mappings(m =>
                    {
                        m.AutoMappings.Add(AutoMap.AssemblyOf<User>().Where(CanMapType).IgnoreBase<BaseEntity>()); //.Conventions.Add<StringColumnLengthConvention>()); 
                        m.FluentMappings.AddFromAssemblyOf<UserMapping>();
                        m.FluentMappings.Conventions.Add(DefaultCascade.SaveUpdate());
                    })
                 //.ExposeConfiguration(config => new SchemaExport(config).SetOutputFile(ConfigurationManager.AppSettings["TempFolder"]+"sinbiota_domain.sql").Create(false, true))
                 .BuildSessionFactory();
        }

        //static readonly IEnumerable<Type> IgnoredTypes = new[]
        //                                             {
        //                                                 typeof (Taxon), 
        //                                             };
        private static bool CanMapType(Type t)
        {
            //if (IgnoredTypes.Contains(t)) return false;
            return t.Namespace == "SinBiota.Model.Entities"; 
        }
    }

    public class StringColumnLengthConvention : IPropertyConvention, IPropertyConventionAcceptance
    {
        public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
        {
            criteria.Expect(x => x.Type == typeof(string)).Expect(x => x.Length == 0);
        }
        public void Apply(IPropertyInstance instance)
        {
            instance.Length(256); // 256 is actually the default; this is here just in case we need to increase it because of the data migration from V1.
        }
    }


}
